package com.egoo.ticket.server.utils.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egoo.eeip.eeif.framework.base.util.common.ObjectUtil;
import com.egoo.ticket.server.config.redis.RedisKeyConstant;
import com.egoo.ticket.server.dao.EwsUserDao;
import com.egoo.ticket.server.dao.WorkOrderDao;
import com.egoo.ticket.server.pojo.entity.WorkOrder;
import com.egoo.ticket.server.service.EurmDataSyncService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author：victor_tang
 * @Date: 2019/10/7
 * @Description: 通用工具类
 */
@Component
@Slf4j
public class CommonUtil {
	@Autowired
	private EwsUserDao ewsUserDao;
	@Autowired
	private WorkOrderDao workOrderDao;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private RestTemplate restTemplate;
	@Value("${server.eurm-server-url}")
	private String eurmUrl;
	@Value("${eurmSynData.limit}")
	private Integer limit;
	@Autowired
	private EurmDataSyncService eurmDataSyncService;
	@Value("${eurmSynData.tenantId}")
	private String eurmTenatIdCode;

	/**
	 * @Author: Donny_dong
	 * @Description: 处理当前创建人
	 * @Param:
	 * @return:
	 * @Date: 2021/1/15
	 */
	public static List<String> handleCurrentCreator(List<String> assignee, WorkOrder workOrder) {
		if (CollectionUtils.isEmpty(assignee)){
			return assignee;
		}
		if (!assignee.contains(ConstantCode.CurrentLoadUser.CURRENT_CREATOR_KEY)){
			return assignee;
		}
		if (assignee.contains(workOrder.getCreateUserId())){
			return assignee;
		}
		assignee.add(workOrder.getCreateUserId());
		return assignee;
	}

	/**
	 * TODO 截取用户所属部门编码
	 *
	 * @param allLinkDeptCode 1
	 * @author: victor_tang
	 * @createtime: 2020/3/24 13:01
	 * @return: java.lang.String
	 */
	public List<String> splitDeptCode(String allLinkDeptCode) {
//		allLinkDeptCode = "[[\"A001\",\"002\"],[\"A001\",\"A001-001\"]]";
//		allLinkDeptCode ="[\"boc_whcs\"],[\"boc_whcs\",\"zdfq\"],[\"boc_whcs\",\"zh_1\"]";
		if (StringUtils.isEmpty(allLinkDeptCode)) {
			return null;
		}
		// 去掉外层[]
		allLinkDeptCode = allLinkDeptCode.substring(1, allLinkDeptCode.length() - 1);

		String[] splitStr = allLinkDeptCode.split("]");
		List<String> deptCodeList = new ArrayList<>();
		for (String allCode : splitStr) {
			Integer index = allCode.lastIndexOf(",");
			String deptCode = "";
			if (index > 0) {
				// 多级截取
				deptCode = allCode.substring(allCode.lastIndexOf(",") + 2,
						allCode.length() - 1);
			} else {
				deptCode = allCode.substring(allCode.lastIndexOf("[") + 2,
						allCode.length() - 1);
			}
			deptCodeList.add(deptCode.trim());
		}
		log.info("转化后的部门编码为：" + deptCodeList.toString());
		return deptCodeList;
	}

	/**
	 * TODO 判断是否含有特殊字符
	 *
	 * @param str 1
	 * @author: victor_tang
	 * @createtime: 2020/4/14 15:21
	 * @return: boolean
	 */
	public static boolean isSpecialChar(String str) {
		String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.find();
	}

	/**
	 * TODO 获取表单字段类型列表
	 *
	 * @param type 1
	 * @author: victor_tang
	 * @createtime: 2020/4/14 15:24
	 * @return: java.lang.String
	 */
	public static String getType(String type) {
		switch (type) {
			case "input":
				type = "单行文本";
				break;
			case "textarea":
				type = "多行文本";
				break;
			case "number":
				type = "计数器";
				break;
			case "radio":
				type = "单选框组";
				break;
			case "checkbox":
				type = "多选框组";
				break;
			case "time":
				type = "时间选择器";
				break;
			case "date":
				type = "日期选择器";
				break;
			case "rate":
				type = "评分";
				break;
			case "color":
				type = "颜色选择器";
				break;
			case "select":
				type = "下拉选择框";
				break;
			case "switch":
				type = "开关";
				break;
			case "slider":
				type = "滑块";
				break;
			case "blank":
				type = "自定义";
				break;
			case "imgupload":
				type = "图片";
				break;
			case "file":
				type = "附件";
				break;
			case "editor":
				type = "编辑器";
				break;
			case "cascader":
				type = "级联选择器";
				break;
			case "city":
				type = "省市区";
				break;
			case "fileupload":
				type = "文件";
				break;
			case "table":
				type = "子表单";
				break;
			case "text":
				type = "HTML";
				break;
			default:
		}
		return type;
	}

	/**
	 * TODO 附件转码
	 *
	 * @param filePath 1
	 * @author: victor_tang
	 * @createtime: 2020/4/14 15:29
	 * @return: java.lang.String
	 */
	public static String encrptToBase64(String filePath) {
		if (filePath == null) {
			return null;
		}
		try {
			byte[] b = Files.readAllBytes(Paths.get(filePath));
			return Base64.getEncoder().encodeToString(b);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * TODO 将MultipartFileToFile转为File
	 *
	 * @param file
	 * @return
	 */
	public File multipartFileToFile(MultipartFile file) {
//		File fileTemp = new File("");
//		String filePath = null;
		File f = null;
		try {
//			filePath = fileTemp.getCanonicalPath();
			String filePath = System.getProperty("user.dir") + "/modelXml";
			File fileTmp = new File(filePath);
			if (!fileTmp.exists()) {
				fileTmp.mkdir();
			}
			filePath += File.separator + file.getOriginalFilename();
			InputStream is = file.getInputStream();
			f = new File(filePath);
			OutputStream os = new FileOutputStream(f);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return f;
	}

	/**
	 * TODO 设置预约回电提醒key过期时间
	 *
	 * @param workOrderId 1
	 * @author: victor_tang
	 * @createtime: 2020/1/14 13:44
	 * @return: void
	 */
	public void setOverDueKeyOfPrepareToWarnPhone(String workOrderId) {
		WorkOrder workOrder = workOrderDao.selectById(workOrderId);
		if (workOrder == null
				|| workOrder.getCustomField() == null
				|| workOrder.getCustomField().getLong("subCallTime") == null
				|| workOrder.getCustomField().getLong("subCallTime") == 0
		) {
			return;
		}
		Long callTime = workOrder.getCustomField().getLong("subCallTime");
		long times = callTime - System.currentTimeMillis();
		if (times <= 0) {
			// 预约回电时间小于当前时间时，直接退出，不在设置预约回电触发点
			return;
		}
		// 设置预约回电触发点
		String callTimePointKey =
				RedisKeyConstant.WORK_ORDER_CALL_TIME_PREFIX + "_" + workOrderId;
		redisUtil.set(callTimePointKey, workOrderId, times);
	}

	public static String checkParamType(String param) {
//		if (ConstantCode.WorkOrderBaseFieldMeanig.WORK_ORDER_ID_FIELD.equals(param)){
//			return "a.id";
//		}else if (ConstantCode.WorkOrderBaseFieldMeanig.STATUS_FIELD.equals(param)){
//			return "a.status_id";
//		}else if (ConstantCode.WorkOrderBaseFieldMeanig.WORK_ORDER_TYPE_FIELD.equals(param)){
//			return "a.work_order_type_id";
//		}else if (ConstantCode.WorkOrderBaseFieldMeanig.CREATE_USER_ID.equals(param)){
//			return "a.create_user_id";
//		}else if (ConstantCode.WorkOrderBaseFieldMeanig.CREATE_TIME.equals(param)){
//			return "a.create_time";
//		}
		String alias = null;
		if (ConstantCode.BelongToTable.WORK_ORDER.equals(param)) {
			alias = "a.";
		} else if (ConstantCode.BelongToTable.WORK_ORDER_RELATION.equals(param)) {
			alias = "b.";
		}
		return alias;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 符号翻译
	 * @Param:
	 * @return:
	 * @Date: 2020/9/2
	 */
	public static String symbolTranslation(String condition) {
		switch (condition) {
			case "=":
				condition = "=";
				break;
			case "≠":
				condition = "!=";
				break;
			case "like":
				condition = "like";
				break;
			case ">":
				condition = ">";
				break;
			case "<":
				condition = "<";
				break;
			case "≥":
				condition = ">=";
				break;
			case "≤":
				condition = "<=";
				break;
			case "∈":
				condition = "contain";
				break;
			default:
		}
		return condition;
	}

	/**
	 * TODO 读取配置文件内容
	 *
	 * @param
	 * @author: victor_tang
	 * @createtime: 2020/9/28 7:57
	 * @return: com.alibaba.fastjson.JSONArray
	 */
	public static JSONArray readConfig(String ralativePath) {
		try {
			String path = System.getProperty("user.dir") + ralativePath;
			File file = new File(path);
			InputStream inputStream = new FileInputStream(file);
			JSONArray arrayJson =
					JSONArray.parseArray(IOUtils.toString(inputStream, "UTF-8"));
			return arrayJson;
		} catch (IOException e) {
			log.error("读取配置文件异常" + e);
			return null;
		}
	}

	public static <T> List<Map<String, Object>> listConvert(List<T> list) {
		List<Map<String, Object>> list_map = new ArrayList<Map<String, Object>>();
		if (list.size() > 0) {
			list.forEach(item -> {
				Map<String, Object> map = null;
				try {
					map = (Map<String, Object>) PropertyUtils.describe(item);
					Set<Map.Entry<String, Object>> entery = map.entrySet();
					Iterator<Map.Entry<String, Object>> it = entery.iterator();
					while (it.hasNext()) {
						Map.Entry<String, Object> en = it.next();
						String key = en.getKey();// 根据键值对对象获取键
					}
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				}
				list_map.add(map);

			});
		}
		return list_map;
	}


	/**
	 * 对象转map 并处理时间为字符串
	 * @param object
	 * @return
	 */
	public static Map<String, Object> ObjectToMap(Object object){
		Map<String,Object> map = JSON.parseObject(JSON.toJSONString(object), Map.class);
		Set<Map.Entry<String, Object>> entery = map.entrySet();
		Iterator<Map.Entry<String, Object>> it = entery.iterator();
		while (it.hasNext()) {
			Map.Entry<String, Object> en = it.next();
			String key = en.getKey();
			if (key.endsWith("Time")) {
				if(ObjectUtil.isNotEmpty(en.getValue())) {
					String timestamp = String.valueOf(en.getValue());// 根据键值对对象获取值
					en.setValue(DateUtils.timeStamp2Date(timestamp,null));
				}
			}
		}

		return map;
	}

	/**
	 * @param str:
	 * @return: java.lang.String
	 * @author: xu
	 * @date: 2020/11/9 18:06
	 * @description:
	 */
	public static String spilt(String str) {
		StringBuffer sb = new StringBuffer();
		String[] temp = str.split(",");
		for (int i = 0; i < temp.length; i++) {
			if (!"".equals(temp[i]) && temp[i] != null) {
				sb.append("'" + temp[i] + "',");
			}
		}
		String result = sb.toString();
		String tp = result.substring(result.length() - 1, result.length());
		if (",".equals(tp)) {
			return result.substring(0, result.length() - 1);
		} else {
			return result;
		}
	}
	/**
	 * TODO 内管提取数据接口
	 * @author: victor_tang
	 * @createtime: 2020/12/8 14:50
	 * @param  bodyJsonObj
	 * @return: com.alibaba.fastjson.JSONObject
	 */
	public JSONObject pubEurmGetData(JSONObject bodyJsonObj){
		if (bodyJsonObj==null) {
			throw new RuntimeException("请求内管body参数不能为空！");
		}
		// 获取租户id
		String tenantId = getTenantId(bodyJsonObj);
		// 移除filters
		bodyJsonObj.remove("filters");
		if (StringUtils.isEmpty(tenantId)) {
			throw new RuntimeException("调用内管数据提取标准接口，租户id不能为空！");
		}
		String csrUrl = eurmUrl + "/if/data/transfer/list.ptc";
		// 设置header参数
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json");
		headers.add("__org",tenantId);
		// 设置body参数
		String jsonData = bodyJsonObj.toString();
		// 组装请求参数
		HttpEntity<String> request = new HttpEntity<>(jsonData, headers);
		log.info("请求内管的参数为==============》" + request);
		//请求接口
		JSONObject jsonObject = restTemplate.postForObject(csrUrl, request,
				JSONObject.class);
		log.info("内管返回数据为==============》" + jsonObject);
		return jsonObject.getJSONObject("info");
	}
	/**
	 * TODO 获取租户id
	 * @author: victor_tang
	 * @createtime: 2020/12/10 11:16
	 * @param bodyJsonObj 1
	 * @return: java.lang.String
	 */
	public String getTenantId(JSONObject bodyJsonObj) {
		JSONArray filters = bodyJsonObj.getJSONArray("filters");
		for (int i = 0; i < filters.size(); i++) {
			JSONObject jsonObject = filters.getJSONObject(i);
			String name = jsonObject.getString("name");
			if (eurmTenatIdCode.equals(name)) {
				return jsonObject.getString("value");
			}
		}
		return null;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 读取数据库铺地文件
	 * @Param:
	 * @return:
	 * @Date: 2021/2/2
	 */
	public static JSONObject readDbData(String ralativePath) {
		try {
			String path = System.getProperty("user.dir") + ralativePath;
			File file = new File(path);
			InputStream inputStream = new FileInputStream(file);

			JSONObject object = JSON.parseObject(IOUtils.toString(inputStream, "UTF-8"));
			return object;
		} catch (IOException e) {
			log.error("读取配置文件异常" + e);
			return null;
		}
	}
}
